import React, {Component} from 'react';
import {Icon, Layout, Menu, Row, Col, Badge, Modal} from 'antd';
import {Route, Switch} from 'react-router-dom';
import logo from '../image/u219.png';

import roleManage from './roleManage';
import adminManage from './adminManage';
import customerManage from './customerManage';
import lineManages from './lineManage';
import carManages from './carManage';
import abnormalList from './abnormalList';
import employeeDetails from './employeeDetails';
import employeeStatistics from './employeeStatistic';
import carStatistics from './carStatistic';
import followStatistics from './followStatistic';
import driverStatistics from './driverStatistic';
import lackDetails from './lackDetails';
import orderDetails from './orderDetails';
import orderManage from './orderManage';
import orderStatistic from './orderStatistic';
import outboundManage from './outboundManage';
import roleAssignment from './roleAssignment';
import storageManage from './storageManage';
import logistic from './logistics';
import menuManage from './menuManage';
import employeeManage from './employeeManage';
import orderDeal from './orderDeal';
import setting from './setting';
import independentLogistics from './independentLogistics';
import marketLogistics from './marketLogistics';
import consignmentManage from './consignmentManage';
import expressManage from './expressManage';
import storageDetails from './storageDetails';
import expressStatistics from './expressStatistic';
import consignmentStatistics from './consignmentStatistic';
import printSetting from './printSetting';

import news from '../image/u253.png';
import exit from '../image/exit.png';

import app from '../AppMethod';
import {menu} from "../value";
import {config} from "../config";

import {Consumer} from "../store";//引入上下文

const {Header, Sider, Content} = Layout;
const SubMenu = Menu.SubMenu;
const confirm = Modal.confirm;

const loop = (menu, data) => {
    let menuList = [];
    data.map((item, index) => {
        if (menu.menu_id === item.menu_parentid) {
            menuList.push(item);
            menu.subList = menuList;
            loop(item, data);
        } else {
            menuList = [];
        }
    })
};

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false,
            key: '0',
            mode: "inline",
            menuListData: [],
            routeList: [
                {path: '/roleManage', component: roleManage},
                {path: '/adminManage', component: adminManage},
                {path: '/menuManage', component: menuManage},
                {path: '/customerManage', component: customerManage},
                {path: '/lineManages', component: lineManages},
                {path: '/carManages', component: carManages},
                {path: '/roleAssignment', component: roleAssignment},
                {path: '/employeeStatistics', component: employeeStatistics},
                {path: '/orderStatistic', component: orderStatistic},
                {path: '/abnormalList', component: abnormalList},
                {path: '/outboundManage', component: outboundManage},
                {path: '/storageManage', component: storageManage},
                {path: '/employeeDetails/:id', component: employeeDetails},
                {path: '/orderManage', component: orderManage},
                {path: '/lackDetails', component: lackDetails},
                {path: '/orderDetails/:id', component: orderDetails},
                {path: '/logistic', component: logistic},
                {path: '/employeeManage', component: employeeManage},
                {path: '/orderDeal', component: orderDeal},
                {path: '/setting', component: setting},
                {path: '/independentLogistics', component: independentLogistics},
                {path: '/marketLogistics', component: marketLogistics},
                {path: '/consignmentManage', component: consignmentManage},
                {path: '/expressManage', component: expressManage},
                {path: '/storageDetails/:id', component: storageDetails},
                {path: '/carStatistics', component: carStatistics},
                {path: '/driverStatistics', component: driverStatistics},
                {path: '/followStatistics', component: followStatistics},
                {path: '/expressStatistics', component: expressStatistics},
                {path: '/consignmentStatistics', component: consignmentStatistics},
                {path: '/printSetting', component: printSetting},
            ],
            current: '1',
            username: 'momo.zxy',
            openKeys: [],
            rootSubmenuKeys: [],
        }
    };

    toggle = () => {
        this.setState({
            collapsed: !this.state.collapsed
        })
    };

    render() {
        const {menuType} = this.props;
        const platForm = '/index';
        return (
            <Layout style={{height: '100%'}}>
                <Sider
                    trigger={null}
                    collapsible={true}
                    collapsed={this.state.collapsed}
                    width="220"
                    height="100%"
                    style={{boxShadow: '2px 0 6px rgba(0,21,41,.35)'}}
                >
                    <Row className="logo" style={{
                        verticalAlign: 'middle',
                        height: '64px',
                        lineHeight: '64px',
                        backgroundColor: '#00284d'
                    }}>
                        <img alt="null" src={logo} style={{width: '150px', marginLeft: '20px'}}/>
                    </Row>
                    <Menu theme="dark" mode="inline" onClick={(e) => this.handleClick(e)}
                          selectedKeys={[this.state.current]} onOpenChange={this.handleOnOpenChange}
                          openKeys={this.state.openKeys}>
                        {
                            this.state.menuListData.map((item, index) => {
                                if (item.subList) {
                                    return (
                                        <SubMenu key={index}
                                                 title={<span><Icon type={item.menu_icon}/><span>{item.menu_name}</span></span>}>
                                            {
                                                item.subList.map((subItem, subIndex) => {
                                                    return (
                                                        <Menu.Item key={platForm + subItem.menu_path}
                                                                   rowKey={index + "_" + subIndex}>
                                                            <span>
                                                                <Icon type={subItem.menu_icon}/>
                                                                <span>{subItem.menu_name}</span>
                                                            </span>
                                                        </Menu.Item>
                                                    )
                                                })
                                            }
                                        </SubMenu>
                                    )
                                } else {
                                    return (
                                        <Menu.Item key={platForm + item.menu_path} rowKey={index}>
                                            <span>
                                                <Icon type={item.menu_icon}/>
                                                <span>{item.menu_name}</span>
                                            </span>
                                        </Menu.Item>
                                    )
                                }
                            })
                        }
                    </Menu>
                </Sider>
                <Layout style={{height: '100%'}}>
                    <Header
                        style={{background: '#fff', paddingLeft: 24, borderBottom: '1px solid #e9e9e9', zIndex: '2'}}>
                        <Icon
                            className="trigger"
                            type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                            onClick={this.toggle}
                            style={{fontSize: '20px', cursor: 'pointer'}}
                        />
                        <span style={{
                            marginLeft: '220px',
                            color: '#f5222d',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}>{config.debug ? "线下版系统" : ''}</span>
                        <Row style={{float: 'right'}}>

                            <span style={{marginLeft: '25px'}}>
                                <span style={{
                                    fontFamily: 'Arial Normal, Arial',
                                    fontWeight: 400,
                                    fontStyle: 'normal', marginLeft: '5px', fontSize: '17px'
                                }}>欢迎您，{this.state.username}
                                </span>
                            </span>
                            <span style={{marginLeft: '15px'}} onClick={() => this.handleExit()}><img alt="exit"
                                                                                                      title="退出"
                                                                                                      src={exit}
                                                                                                      style={{
                                                                                                          width: '24px',
                                                                                                          height: '24px',
                                                                                                          cursor: 'pointer'
                                                                                                      }}/></span>
                        </Row>
                    </Header>
                    <div style={{background: '#fff', paddingLeft: 24}}>
                        <div style={{fontSize: '18px', paddingBottom: '15px', paddingTop: '15px'}}>{menuType}</div>
                    </div>
                    <Content style={{margin: '0px', padding: 24, backgroundColor: '#fff', margin: 24}}>
                        <Switch>
                            {
                                this.state.routeList.map((item, index) => {
                                    return (
                                        <Route key={index} path={platForm + item.path} component={item.component}/>
                                    )
                                })
                            }
                        </Switch>
                    </Content>
                </Layout>
            </Layout>
        )
    };

    componentDidMount() {
        let selectKey = app.getData('selectKey');
        console.log(selectKey);
        let openKeys = app.getData('openKeys');
        if (selectKey) {
            this.setState({current: selectKey});
        }
        if (openKeys && openKeys.length > 0) {
            this.setState({openKeys: openKeys});
        }
        window._this = this;
        this.handleSearchMenuList();
    };

    /**
     * 处理菜单栏点击跳转页面
     * @param e
     */
    handleClick = (e) => {
        this.setState({
            current: e.key,
        });
        app.setData('selectKey', e.key);
        this.props.history.push(e.key);
    };

    /**
     * 获取菜单栏列表
     */
    handleSearchMenuList() {
        let token = app.getToken();
        let firstMenu = [];
        if (!token) {
            app.alert("您还未登录", "error", 3);
            this.props.history.push("/login");
            return;
        } else {
            let username = app.getData("username");
            this.setState({username});
            let menuList = app.getData("menu");
            if (menuList && menuList.length > 0) {
                menuList.map((item) => {
                    if (item.menu_level === 1) {
                        firstMenu.push(item);
                    }
                });
                firstMenu.map((item) => {
                    loop(item, menuList);
                });
                console.log(firstMenu);
                this.setState({menuListData: firstMenu});
            } else {
                this.setState({menuListData: []});
            }
        }
        this.handleGetMenuKey(firstMenu);
    };

    /**
     * 获取菜单key
     */
    handleGetMenuKey(menuListData) {
        let keyData = [];
        menuListData.map((item, index) => {
            if (item.subList) {
                index = index.toString();
                keyData.push(index);
            }
        });
        console.log(keyData);
        this.setState({rootSubmenuKeys: keyData});
    }

    /**
     * 处理菜单栏展开/收起操作
     * @param openKeys
     */
    handleOnOpenChange = (openKeys) => {
        let latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        if (this.state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            this.setState({openKeys});
            app.setData('openKeys', JSON.stringify(openKeys));
        } else {
            let openKeys = latestOpenKey ? [latestOpenKey] : [];
            this.setState({
                openKeys: openKeys,
            });
            app.setData('openKeys', JSON.stringify(openKeys));
        }
    };

    /**
     * 处理退出系统事件
     */
    handleExit() {
        const _this = this;
        confirm({
            title: '',
            content: '您确认退出吗？',
            onOk() {
                app.removeToken();
                app.removeDate("menu");
                app.removeDate("username");
                _this.props.history.push('/login');
            },
            onCancel() {

            }
        })
    }
}

export default prop => (
    <Consumer>
        {
            props => (
                <Index {...prop} {...props}/>
            )
        }
    </Consumer>
);